package gopdf

import (
	"errors"
	"strings"

	wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

type gopdf struct {
	head string //html中heade标签内部分
	body string //html中body标签内部分
	html string //html中html标签内部分
	url  string //指定网址
}

func New() *gopdf {
	return &gopdf{}
}

//<meta charset="UTF-8">
func (pdf *gopdf) SetHead(head string) {
	pdf.head = head
}

//<h1 style="color:green;">测试一下中文<h1><img src="http://api.qrserver.com/v1/create-qr-code/?data=HelloWorld" alt="img" height="42" width="42"></img>
func (pdf *gopdf) SetBody(body string) {
	pdf.body = body
}

//<head></head><body></body>
func (pdf *gopdf) SetHtml(html string) {
	pdf.html = html
}

//指定网址
func (pdf *gopdf) SetUrl(_url string) {
	pdf.url = _url
}

//保存
func (pdf *gopdf) Save(filepath string) error {
	if filepath == "" {
		return errors.New("路径为空")
	}

	htmlpdf, e := wkhtml.NewPDFGenerator()
	if e != nil {
		return e
	}

	if pdf.url != "" {
		htmlpdf.AddPage(wkhtml.NewPage(pdf.url))
	} else {
		htmlStr := `<html>`
		if pdf.html != "" {
			htmlStr += pdf.html + `</html>`
		} else {
			if pdf.head != "" {
				htmlStr += `<head>` + pdf.head + `</head>`
			} else {
				htmlStr += `<head><meta charset="UTF-8"></head>`
			}

			if pdf.body != "" {
				htmlStr += `<body>` + pdf.body + `</body>`
			} else {
				htmlStr += `<body>内容是空的</body>`
			}

			htmlStr += `</html>`
		}

		htmlpdf.AddPage(wkhtml.NewPageReader(strings.NewReader(htmlStr)))
	}

	e = htmlpdf.Create()
	if e != nil {
		return e
	}

	e = htmlpdf.WriteFile(filepath)
	if e != nil {
		return e
	}

	return nil
}
